#include "common.h"
#include <openssl/rand.h>
#include <string.h>
#include <stdio.h>

void compute_sm3_hash(const char *password, const char *salt, unsigned char *hash) {
	    unsigned char data[MAX_PASSWORD_LEN + SM3_DIGEST_LENGTH];
	        snprintf((char *)data, sizeof(data), "%s%s", password, salt);
		    SM3(data, strlen((char *)data), hash);
}

void generate_salt(char *salt, size_t len) {
	    if (len < SM3_DIGEST_LENGTH) return;
	        RAND_bytes((unsigned char *)salt, SM3_DIGEST_LENGTH);
}

void sm4_encrypt(const unsigned char *key, const unsigned char *plaintext, 
		                unsigned char *ciphertext, size_t len) {
	    SM4_KEY sm4_key;
	        SM4_set_key(key, &sm4_key);
		    
		    size_t blocks = len / 16;
		        if (len % 16 != 0) blocks++;
			    
			    unsigned char block[16];
			        for (size_t i = 0; i < blocks; i++) {
					        size_t block_len = (i == blocks - 1) ? len % 16 : 16;
						        if (block_len == 0) block_len = 16;
							        
							        memset(block, 0, 16);
								        memcpy(block, plaintext + i*16, block_len);
									        SM4_encrypt(block, ciphertext + i*16, &sm4_key);
										    }
}

void sm4_decrypt(const unsigned char *key, const unsigned char *ciphertext, 
		                unsigned char *plaintext, size_t len) {
	    SM4_KEY sm4_key;
	        SM4_set_key(key, &sm4_key);
		    
		    size_t blocks = len / 16;
		        if (len % 16 != 0) blocks++;
			    
			    unsigned char block[16];
			        for (size_t i = 0; i < blocks; i++) {
					        SM4_decrypt(ciphertext + i*16, plaintext + i*16, &sm4_key);
						    }
}
